<template>
  <div class="todo-footer">
    <label>
      <input
        type="checkbox"
        v-model="selectAll"
        v-bind="todoList.length ? {} : { disabled: 'disabled' }"
      />
    </label>
    <span>
      <span>已完成{{ quantityCompleted }}</span> / 全部{{ todoList.length }}
    </span>
    <button class="btn btn-danger" @click="deletecompleted">
      清除已完成任务
    </button>
  </div>
</template>

<script>
import PubSub from "pubsub-js";
import lodash from "lodash";

export default {
  name: "Footer",
  data() {
    return {
      todoList: [],
    };
  },
  computed: {
    selectAll: {
      get() {
        return this.todoList.every((item) => item.done) && this.todoList.length;
      },
      set(value) {
        /* 触发全选/反选事件 */
        this.$bus.$emit("selectAll", value)
      },
    },
    quantityCompleted() {
      return this.todoList.reduce((p, c) => (c.done ? p + 1 : p), 0);
    },
  },
  methods: {
    deletecompleted() {
      this.$bus.$emit("deleteCompleted")
    },
  },
  /* 因为，List 中的发布是在 mounted 中的并且不是异步的(正常开发下一般不会)，订阅要在发布前所以这里使用 beforeMount */
  beforeMount() {
    /* 绑定获取 todoList 数据的事件 */
    this.$bus.$on("getTodoList", (todoList) => {
      this.todoList = lodash.cloneDeep(todoList)
    });
  },
  beforeDestroy() {
    this.$bus.$off(["getTodoList"])
  }
};
</script>

<style scoped>
/*footer*/
.todo-footer {
  height: 40px;
  line-height: 40px;
  padding-left: 6px;
  margin-top: 5px;
}

.todo-footer label {
  display: inline-block;
  margin-right: 20px;
  cursor: pointer;
}

.todo-footer label input {
  position: relative;
  top: -1px;
  vertical-align: middle;
  margin-right: 5px;
}

.todo-footer button {
  float: right;
  margin-top: 5px;
}
</style>